package com.zry.pda.ui.activity


import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.KeyEvent
import android.view.View
import com.zry.pda.R
import com.zry.pda.been.LoginInfoBean
import com.zry.pda.databinding.ActivityLoginBinding
import com.zry.pda.presenter.HttpServer
import com.zry.pda.presenter.LoginPresenter
import com.zry.pda.ui.base.BaseActivity
import com.zry.pda.utils.SpUtil
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.common_title.*

class LoginActivity : BaseActivity() {
    private var activityLoginBinding: ActivityLoginBinding? = null
    private var loginPresenter: LoginPresenter? = null
    private var loginInfoBean: LoginInfoBean? = null
    private var password: String? = null
    private var username: String? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_login
    }

    override fun initData() {
        activityLoginBinding = viewDataBinding as ActivityLoginBinding
        loginPresenter = LoginPresenter(this)
        activityLoginBinding?.handlerClick = loginPresenter

        titleCenterText.text = getString(R.string.Login)
        commonLeftLinearLayout.visibility = View.GONE

        initView()
    }


    private fun initView() {
        password = SpUtil().getString(this, "password")
        username = SpUtil().getString(this, "username")
        if (password != null && password != "" && username != null && username != "") {
            loginInfoBean = SpUtil().getObject(this, "loginInfoBean")!!
        }
        loginAccount.setText(username)
        loginPassword.setText(password)

        displayPassword.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                //如果选中，显示密码
                loginPassword.transformationMethod = HideReturnsTransformationMethod.getInstance()
            } else {
                //否则隐藏密码
                loginPassword.transformationMethod = PasswordTransformationMethod.getInstance()
            }
        }

        loginPassword.setOnKeyListener { v, keyCode, event ->
            if (keyCode == KeyEvent.ACTION_DOWN) {
                loginPresenter?.getEditString()
                loginPresenter?.loginApi(loginAccount.text.toString().trim(), loginPassword.text.toString().trim())
                return@setOnKeyListener true
            }
            return@setOnKeyListener false
        }

        commonLeftLinearLayout.setOnClickListener { this.finish() }
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (((keyCode == KeyEvent.KEYCODE_BACK) || (keyCode == KeyEvent.KEYCODE_HOME)) && event?.repeatCount == 0) {
            myActivityManager?.AppExit()
        }
        return super.onKeyDown(keyCode, event)
    }
}
